﻿///***************************************************************
/// 시  스  템 : Updms.Crd
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd1013m
/// 파  일  명 : Crd1013m.aspx.cs
/// 설      명 : 할부사용내역
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-21 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd1013m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Crd1013m";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Crd crd = new CommCode.Crd(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = 12;//GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//카드명
		protected string kw2 = "";	//계정
		protected string kw3 = "";	//카드사용일(부터)
		protected string kw4 = "";	//카드사용일(까지)

		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드
		private string gs_page_mode = "";

		//외부페이지에서 호출
		protected string gs_external = "";

		//페이지별합계
		decimal ld_amount = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();			
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SetPaymntDtList(ddl_search_card_cd.SelectedValue);
				SelectProcess();
			}
			SetClientScriptNoPostBack();
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetCardInfoList();
			SetAccount();
			CreateInsCd();
			SetSearchParameter();
			SetCardInfo();
		}

		#endregion
		
		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}
		
		#endregion

		#region SetClientScript, SetClientScriptNoPostBack

		private void SetClientScript()
		{
			//엔터검색
			ddl_search_card_cd.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_biz_from_dt.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_biz_to_dt.Attributes.Add("onkeypress", "enterSearchOnPage(event)");

			//달력콘트롤 설정
			ce_biz_dt.SelectedDate = DateTime.Now.AddDays(0);

			//onKeyUp이벤트
			txt_amount.Attributes.Add("onkeyup", "form1.txt_amount.value=addComma(form1.txt_amount.value);");
		}

		//포스트백과 무관하게 이벤트 지정
		private void SetClientScriptNoPostBack()
		{
			//계정
			cbl_search_account.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_account');");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();

			gs_external = String.IsNullOrEmpty(Request.QueryString["external"]) ? "" : Request.QueryString["external"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_card_cd.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_card_cd.SelectedValue = kw1;
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))
					{
						kw2 = WebControlUtil.GetCheckBoxListValue(cbl_search_account, 1);
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_account, kw2);
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_biz_from_dt.Text))
						{
							kw3 = DateUtil.GetMonthEx(-12);	//오늘부터 12개월전
							txt_search_biz_from_dt.Text = kw3;
						}
						else
						{
							kw3 = txt_search_biz_from_dt.Text.Trim();
						}
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_biz_from_dt.Text = kw3;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_biz_to_dt.Text))
						{
							kw4 = DateUtil.GetMonthEx(0);	// 오늘
							txt_search_biz_to_dt.Text = kw4;
						}
						else
						{
							kw4 = txt_search_biz_to_dt.Text.Trim();
						}
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						txt_search_biz_to_dt.Text = kw4;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_card_cd.SelectedValue;
					kw2 = WebControlUtil.GetCheckBoxListValue(cbl_search_account, 1);
					kw3 = String.IsNullOrEmpty(txt_search_biz_from_dt.Text) ? DateUtil.GetMonthEx(-12) : txt_search_biz_from_dt.Text.Trim();
					kw4 = String.IsNullOrEmpty(txt_search_biz_to_dt.Text) ? DateUtil.GetMonthEx(0) : txt_search_biz_to_dt.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ddl_search_card_cd.SelectedItem.Text;
			string ls_kw2 = WebControlUtil.GetCheckBoxListText(cbl_search_account, 1);

			lbl_search_keyword.Text = ls_kw1 + " / " + ls_kw2 + " / " + kw3 + " ~ " + kw4;
		}

		#endregion

		#region 마스터 Method (SetCardInfoList, SetAccount)

		//카드정보
		private void SetCardInfoList()
		{
			DataSet lo_ds = new DataSet();
			Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT();

			lo_ds.Merge(_Crd1010m_NT.GetCardInfoList("Y"));

			ddl_search_card_cd.Items.Clear();
			ddl_search_card_cd.DataSource = lo_ds;
			ddl_search_card_cd.DataMember = "UPDMS_CRD_INFO";
			ddl_search_card_cd.DataTextField = "Card_Nm";
			ddl_search_card_cd.DataValueField = "Card_Cd";
			ddl_search_card_cd.DataBind();
		}

		//계정
		private void SetAccount()
		{
			crd.SetAccount(cbl_search_account);
			crd.SetAccount(ddl_account);

			cbl_search_account.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}
		
		#endregion

		#region 디테일1 Method (SetCardInfo, SetPaymntDtList, CreateInsCd, SetInsStartDt, SetInsEndDt)

		//카드이미지
		private void SetCardInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), ddl_search_card_cd.SelectedValue);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//카드정보(이미지)
			using (Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT())
			{
				lo_ds.Merge(_Crd1010m_NT.GetCardInfo(lo_dp));
			}

			string ls_card_image = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Attach_File1");
			img_card_image.Src = FILE_PATH_UPLOAD_WEB_PATH + (string.IsNullOrEmpty(ls_card_image) ? "empty.png" : ls_card_image);
		}

		//카드코드별 결제예정일
		private void SetPaymntDtList(string ls_card_cd)
		{
			ddl_ins_st_dt.Items.Clear();
			ddl_ins_ed_dt.Items.Clear();

			DataSet lo_ds = new DataSet();
			Crd1011m_NT _Crd1011m_NT = new Crd1011m_NT();

			lo_ds.Merge(_Crd1011m_NT.GetPaymntDtList(ls_card_cd));

			ddl_ins_st_dt.Items.Clear();
			ddl_ins_st_dt.DataSource = lo_ds;
			ddl_ins_st_dt.DataMember = "UPDMS_CRD_PAYMNT_DT";
			ddl_ins_st_dt.DataTextField = "Text";
			ddl_ins_st_dt.DataValueField = "Value";
			ddl_ins_st_dt.DataBind();

			ddl_ins_ed_dt.Items.Clear();
			ddl_ins_ed_dt.DataSource = lo_ds;
			ddl_ins_ed_dt.DataMember = "UPDMS_CRD_PAYMNT_DT";
			ddl_ins_ed_dt.DataTextField = "Text";
			ddl_ins_ed_dt.DataValueField = "Value";
			ddl_ins_ed_dt.DataBind();

			if (ddl_ins_st_dt.Items.Count > 0)
			{
				ibtn_save.Enabled = true;
				ibtn_delete.Enabled = true;
			}
			else
			{
				ibtn_save.Enabled = false;
				ibtn_delete.Enabled = false;
				CallMsgBoxInAjax("MSG_ERR_142");	//지정된 결제일이 없습니다.\n'카드결제일관리'에서 추가해 주세요
			}
		}

		//할부코드(Ins_Cd)를 생성한다.
		private void CreateInsCd()
		{
			Crd1013m_NT _Crd1013m_NT = new Crd1013m_NT();

			//DB에 등록된 할부코드의 현재년도별 최근값을 가져온다.
			lbl_ins_cd.Text = _Crd1013m_NT.GetLastInsCd(DateUtil.GetNow("yyyy"));
		}
		
		//할부시작일
		private void SetInsStartDt()
		{
			string ls_paymnt_dt = String.Empty;
			DataPack lo_dp = new DataPack();

			if (String.IsNullOrEmpty(txt_biz_dt.Text))
			{
				CallMsgBoxInAjax("MSG_ERR_118");	//카드사용일을 먼저 입력하세요
			}
			else
			{
				Crd1011m_NT _Crd1011m_NT = new Crd1011m_NT();
				lo_dp.AddProperty("ls_card_cd", typeof(string), ddl_search_card_cd.SelectedValue);
				lo_dp.AddProperty("ls_biz_dt", typeof(string), txt_biz_dt.Text.Trim());

				ls_paymnt_dt = _Crd1011m_NT.GetPaymntDtByBizDt(lo_dp);

				ddl_ins_st_dt.SelectedValue = ls_paymnt_dt;
			}
		}

		//할부종료일
		private void SetInsEndDt()
		{
			if (String.IsNullOrEmpty(txt_ins_total_cnt.Text))
			{
				CallMsgBoxInAjax("MSG_ERR_119");	//총할부차수를 먼저 입력하세요
			}
			else
			{
				int li_ins_total_cnt = Convert.ToInt32(txt_ins_total_cnt.Text) - 1;
				if (ddl_ins_ed_dt.Items.Count - 1 >= ddl_ins_st_dt.SelectedIndex + li_ins_total_cnt)
				{
					ddl_ins_ed_dt.SelectedIndex = ddl_ins_st_dt.SelectedIndex + li_ins_total_cnt;
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_117");	//적용할 할부종료일이 없습니다.'카드결제일관리'에서 추가해 주세요
				}
			}
		}		

		#endregion

		#region 디테일2 Method (AddInsRepayListAttribute, setCalcRepayAmount, IsConfirmYn)

		//텍스트박스에 콤마자동추가 어트리뷰트 추가
		private void AddInsRepayListAttribute()
		{
			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				TextBox tb_ins_capital = (TextBox)GridView2.Rows[i].FindControl("txt_ins_capital");
				TextBox tb_ins_interest = (TextBox)GridView2.Rows[i].FindControl("txt_ins_interest");
				TextBox tb_ins_month_amt = (TextBox)GridView2.Rows[i].FindControl("txt_ins_month_amt");
				TextBox tb_ins_balance = (TextBox)GridView2.Rows[i].FindControl("txt_ins_balance");

				string ls_temp1 = "form1." + tb_ins_capital.ClientID + ".value=addComma(form1." + tb_ins_capital.ClientID + ".value);";
				string ls_temp2 = "form1." + tb_ins_interest.ClientID + ".value=addComma(form1." + tb_ins_interest.ClientID + ".value);";
				string ls_temp3 = "form1." + tb_ins_month_amt.ClientID + ".value=addComma(form1." + tb_ins_month_amt.ClientID + ".value);";
				string ls_temp4 = "form1." + tb_ins_balance.ClientID + ".value=addComma(form1." + tb_ins_balance.ClientID + ".value);";

				tb_ins_capital.Attributes.Add("onkeyup", ls_temp1);
				tb_ins_interest.Attributes.Add("onkeyup", ls_temp2);
				tb_ins_month_amt.Attributes.Add("onkeyup", ls_temp3);
				tb_ins_balance.Attributes.Add("onkeyup", ls_temp4);
			}
		}
		
		//차수별할부금 배분
		private void setCalcRepayAmount()
		{
			//할부원금
			int li_amount = ConversionUtil.ExtractNumberInt(txt_amount.Text);
			
			//총할부차수
			int li_ins_total_cnt = ConversionUtil.ExtractNumberInt(txt_ins_total_cnt.Text);

			int li_1st_amount = 0;	//1개월차 월불입금
			int li_2nd_amount = 0;	//2개월차이후 월불입금
			int li_pre_ins_balance = 0;	//앞차수잔액

			//원금을 총할부차수로 나눈 나머지가 0이면
			int li_div = ((li_amount % li_ins_total_cnt) == 0) ? 0 : 1;	
			
			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				TextBox tb_ins_capital		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_capital");	//월불입금
				TextBox tb_ins_interest		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_interest");	//이자
				TextBox tb_ins_month_amt	= (TextBox)GridView2.Rows[i].FindControl("txt_ins_month_amt");	//월납입금
				TextBox tb_ins_balance		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_balance");	//잔액

				if (i == 0)
				{
					//1개월차월불입금이 0이 아니면(입력후 배분)
					if (tb_ins_capital.Text != "0")
					{
						li_1st_amount = ConversionUtil.ExtractNumberInt(tb_ins_capital.Text);
					}
					else
					{
						//1개월차 월불입금 = round(할부원금/총할부차수,0)
						li_1st_amount = Convert.ToInt32(Math.Round(Convert.ToDouble(li_amount) / Convert.ToDouble(li_ins_total_cnt))) + li_div;
					}
					
					for (int j = 0; j<li_ins_total_cnt; j++)
					{
						//원금 - 1개월차월불입금을 (총할부차수 - 1)로 나눈 나머지가 0이아니면 1개월차월불입금+1 해준다.
						if ((Convert.ToDouble(li_amount) - Convert.ToDouble(li_1st_amount)) % (li_ins_total_cnt - 1) != 0)
						{
							li_1st_amount = li_1st_amount + 1;
						}
					}
					
					tb_ins_capital.Text = li_1st_amount.ToString("#,###,##0");
					tb_ins_interest.Text = "0";
					tb_ins_month_amt.Text = li_1st_amount.ToString("#,###,##0");
					tb_ins_balance.Text = (li_amount - li_1st_amount).ToString("#,###,##0");

				}
				else
				{
					//2개월차이후 월불입금 = 할부원금 - 1개월차 월불입금 / 총할부차수 - 1
					li_2nd_amount = Convert.ToInt32(Math.Round((Convert.ToDouble(li_amount) - Convert.ToDouble(li_1st_amount)) / (li_ins_total_cnt - 1)));
					
					tb_ins_capital.Text = li_2nd_amount.ToString("#,###,##0");
					tb_ins_interest.Text = "0";
					tb_ins_month_amt.Text = li_2nd_amount.ToString("#,###,##0");

					//잔액 = 앞차수잔액 - 현재월불입금
					TextBox tb_pre_ins_balance = (TextBox)GridView2.Rows[i - 1].FindControl("txt_ins_balance");	//앞차수잔액
					
					li_pre_ins_balance = ConversionUtil.ExtractNumberInt(tb_pre_ins_balance.Text) - ConversionUtil.ExtractNumberInt(tb_ins_month_amt.Text);
					tb_ins_balance.Text = li_pre_ins_balance.ToString("#,###,##0");
				}
			}
		}

		// 할부상환리스트 금액검증
		private string IsValidInsRepayList()
		{
			string ls_rslt = "OK";
			
			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				TextBox tb_ins_capital		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_capital");
				TextBox tb_ins_interest		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_interest");
				TextBox tb_ins_month_amt	= (TextBox)GridView2.Rows[i].FindControl("txt_ins_month_amt");
				TextBox tb_ins_balance		= (TextBox)GridView2.Rows[i].FindControl("txt_ins_balance");				

				//이전달잔액
				TextBox tb_ins_balance_pre = new TextBox();
				int li_ins_balance_pre = 0;

				//이전달잔액, 2개월차부터 계산
				if (i > 0)
				{
					tb_ins_balance_pre = (TextBox)GridView2.Rows[i - 1].FindControl("txt_ins_balance");
					li_ins_balance_pre = ConversionUtil.ExtractNumberInt(tb_ins_balance_pre.Text);
				}

				int li_amount			= ConversionUtil.ExtractNumberInt(txt_amount.Text);		//결제금액
				int li_ins_capital		= ConversionUtil.ExtractNumberInt(tb_ins_capital.Text);	//월불입금
				int li_ins_interest		= ConversionUtil.ExtractNumberInt(tb_ins_interest.Text);	//이자
				int li_ins_month_amt	= ConversionUtil.ExtractNumberInt(tb_ins_month_amt.Text);	//월납입금
				int li_ins_balance		= ConversionUtil.ExtractNumberInt(tb_ins_balance.Text);	//잔액

				//월납입금 = 월불입금 + 이자
				if (li_ins_month_amt != (li_ins_capital + li_ins_interest))
				{
					ls_rslt = (i + 1) + GetXmlMsg("STR_005");	//개월차 월납입금의 금액을 확인하세요
					return ls_rslt;
				}

				//잔액 = 결제금액 - 월납입금 (1개월차)
				if (li_ins_balance != (li_amount - li_ins_month_amt) && (i == 0))
				{
					ls_rslt = "1" + GetXmlMsg("STR_006");	//개월차 잔액을 확인하세요
					return ls_rslt;
				}
				//잔액 = 결제금액 - 월납입금 (2개월차부터)
				else if (li_ins_balance != (li_ins_balance_pre - li_ins_month_amt) && (i != 0))
				{
					ls_rslt = (i + 1) + GetXmlMsg("STR_006");	//개월차 잔액을 확인하세요
					return ls_rslt;
				}

				//마지막차수의 잔액은 0이어야 한다.
				if (i == (GridView2.Rows.Count - 1) && li_ins_balance != 0)
				{
					ls_rslt = GetXmlMsg("STR_007");	//마지막차수의 잔액은 0이어야 합니다
					return ls_rslt;
				}
			}
			return ls_rslt;
		}

		#endregion

		#region CRUD 할부사용내역 (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_account", typeof(string), kw2);
			lo_dp.AddProperty("ls_biz_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_biz_dt_to", typeof(string), kw4);

			using (Crd1013m_NT _Crd1013m_NT = new Crd1013m_NT())
			{
				li_row_count = _Crd1013m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Crd1013m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			string search_condition = "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&page=";

			Pager pager = new Pager(this, ref lbl_page);
			pager.PageNavigation(
				li_cur_page,
				li_page_count,
				gs_path_info + search_condition);

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = li_row_count.ToString("#,###,##0");

			//즐겨찾기
			ibtn_favorite.Attributes.Add("onclick", "javascript:goFavoriteSearchPage('" + PID + "','" + search_condition + "');return false;");

			//외부에서 호출되면서 결과값이 1개이면 자동바인딩
			if (gs_external != "" && li_row_count == 1)
			{
				BindingGridView(GridView1, 0);
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Crd1013m_RT _Crd1013m_RT = new Crd1013m_RT())
			{
				int li_return = _Crd1013m_RT.InsertProcess(SetValue());

				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Crd1013m_RT _Crd1013m_RT = new Crd1013m_RT())
			{
				int li_return = _Crd1013m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다				
				CallMsgBoxInAjax(ls_msg_id);
				
				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Crd1013m_RT _Crd1013m_RT = new Crd1013m_RT())
			{
				int li_return = _Crd1013m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			gs_page_mode = "R";
			SetSearchParameter();
			ClearValue();
			CreateInsCd();
			SelectProcess();
			SetPaymntDtList(ddl_search_card_cd.SelectedValue);
			//ChangePageMode();
		}

		#endregion

		#region CRUD 할부상환리스트 (SelectRepayList, UpdateRepayProcess, ConfirmProcess)

		//등록된 할부상환리스트 출력
		private void SelectRepayList(string ls_card_cd, string ls_ins_cd)
		{
			DataSet lo_ds = new DataSet();
			
			using (Crd1013m_NT _Crd1013m_NT = new Crd1013m_NT())
			{
				lo_ds.Merge(_Crd1013m_NT.SelectRepayList(ls_card_cd, ls_ins_cd));
			}
			
			GridView2.DataSource = lo_ds;
			GridView2.DataBind();

			//콤마자동추가 어트리뷰트 추가
			AddInsRepayListAttribute();
		}
		
		
		// 할부상환관리 저장(업데이트)
		private void UpdateRepayProcess()
		{
			int li_return = 0;
			Crd1013m_RT _Crd1013m_RT = new Crd1013m_RT();
			
			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				li_return = _Crd1013m_RT.UpdateRepay(SetValueRepay(i));
			}

			string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
			CallMsgBoxInAjax(ls_msg_id);
			
			SearchProcess();
		}

		//확정
		private void ConfirmProcess(int li_seq, string ls_confirm_yn)
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("li_seq", typeof(int), li_seq);
			lo_dp.AddProperty("ls_user_id", typeof(string), USER_ID);

			using (Crd1013m_RT _Crd1013m_RT = new Crd1013m_RT())
			{
				int li_return = _Crd1013m_RT.ConfirmProcess(lo_dp);	// 확정처리 ↔ 확정취소

				string ls_msg_id = (ls_confirm_yn == "N") ? "MSG_INF_008" : "MSG_INF_020";//확정되었습니다:해제되었습니다
				ls_msg_id = (li_return > 0) ? ls_msg_id : "MSG_ERR_106";	//확정(해제)되었습니다:확정할 수 없습니다

				CallMsgBoxInAjax(ls_msg_id);
			}
		}
		
		#endregion

		#region SetValue, SetValueRepay, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			
			lo_dp.AddProperty("Seq",			typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Card_Cd",		typeof(string), ddl_search_card_cd.SelectedValue);
			lo_dp.AddProperty("Ins_Cd",			typeof(string), lbl_ins_cd.Text);
			lo_dp.AddProperty("Account",		typeof(string), ddl_account.SelectedValue);
			lo_dp.AddProperty("Contents",		typeof(string), txt_contents.Text);
			lo_dp.AddProperty("Amount",			typeof(string), ConversionUtil.ExtractNumberStr(txt_amount.Text));
			lo_dp.AddProperty("Ins_Total_Cnt",	typeof(string), ConversionUtil.ExtractNumberStr(txt_ins_total_cnt.Text));
			lo_dp.AddProperty("Biz_Dt",			typeof(string), txt_biz_dt.Text);
			lo_dp.AddProperty("Ins_St_Dt",		typeof(string), ddl_ins_st_dt.SelectedValue);
			lo_dp.AddProperty("Ins_Ed_Dt",		typeof(string), ddl_ins_ed_dt.SelectedValue);
			lo_dp.AddProperty("Remark",			typeof(string), ConversionUtil.DefaultValue(txt_remark.Text));
			lo_dp.AddProperty("Paymnt_Yn",		typeof(string), rbl_paymnt_yn.SelectedValue);
			lo_dp.AddProperty("Latitude",		typeof(string), ConversionUtil.DefaultValue(txt_latitude.Text, ""));
			lo_dp.AddProperty("Longitude",		typeof(string), ConversionUtil.DefaultValue(txt_longitude.Text, ""));
			lo_dp.AddProperty("Create_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt",		typeof(string), "");
			lo_dp.AddProperty("Update_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt",		typeof(string), "");
			
			return lo_dp;
		}

		//SetValueRepay
		private DataPack SetValueRepay(int li_index)
		{
			DataPack lo_dp = new DataPack();
			
			TextBox tb_ins_capital		= (TextBox)GridView2.Rows[li_index].FindControl("txt_ins_capital");
			TextBox tb_ins_interest		= (TextBox)GridView2.Rows[li_index].FindControl("txt_ins_interest");
			TextBox tb_ins_month_amt	= (TextBox)GridView2.Rows[li_index].FindControl("txt_ins_month_amt");
			TextBox tb_ins_balance		= (TextBox)GridView2.Rows[li_index].FindControl("txt_ins_balance");
			
			lo_dp.AddProperty("Seq",			typeof(string), "");
			lo_dp.AddProperty("Card_Cd",		typeof(string), ddl_search_card_cd.SelectedValue);
			lo_dp.AddProperty("Ins_Cd",			typeof(string), GridView2.Rows[li_index].Cells[3].Text);
			lo_dp.AddProperty("Ins_Cnt",		typeof(string), ConversionUtil.ExtractNumberStr(GridView2.Rows[li_index].Cells[6].Text));
			lo_dp.AddProperty("Paymnt_Dt",		typeof(string), GridView2.Rows[li_index].Cells[7].Text);
			lo_dp.AddProperty("Ins_Capital",	typeof(string), ConversionUtil.ExtractNumberStr(tb_ins_capital.Text));
			lo_dp.AddProperty("Ins_Interest",	typeof(string), ConversionUtil.ExtractNumberStr(tb_ins_interest.Text));
			lo_dp.AddProperty("Ins_Month_Amt",	typeof(string), ConversionUtil.ExtractNumberStr(tb_ins_month_amt.Text));
			lo_dp.AddProperty("Ins_Balance",	typeof(string), ConversionUtil.ExtractNumberStr(tb_ins_balance.Text));
			lo_dp.AddProperty("Create_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt",		typeof(string), "");
			lo_dp.AddProperty("Update_User",	typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt",		typeof(string), "");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			ddl_account.SelectedIndex = 0;
			txt_contents.Text = "";
			txt_amount.Text = "";
			txt_ins_total_cnt.Text = "";
			ce_biz_dt.SelectedDate = DateTime.Now.AddDays(0);
			txt_remark.Text = "";
			rbl_paymnt_yn.SelectedIndex = 1;
			txt_latitude.Text = "";
			txt_longitude.Text = "";
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);
		}		
		
		// ChangePageMode
		private void ChangePageMode()
		{
			string grdId = String.Empty;
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					table_installment_repay.Visible = false;
					grdId = "GridView1";
					break;
				case "R":	// 검색버튼 클릭시
					table_installment_repay.Visible = false;
					grdId = "GridView1";
					break;
				case "U":	// ItemCommand 이벤트
					table_installment_repay.Visible = true;
					grdId = "GridView2";
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET), grdId);
		}
		
		#endregion

		#region GridView1이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//비고
				e.Row.Cells[8].Attributes.Add("title", GridView1.DataKeys[e.Row.RowIndex].Values["Remark"].ToString());

				//결제완료
				switch (e.Row.Cells[15].Text)
				{
					case "Y":
						e.Row.Cells[15].Attributes.Add("class", "color_gray");
						break;
					case "N":
						e.Row.Cells[15].Attributes.Add("class", "color_darkred");
						break;
					default:
						e.Row.Cells[15].Attributes.Add("class", "color_gray");
						break;
				}

				//삭제가능한 항목만 체크박스 활성화
				HtmlInputCheckBox cb = (HtmlInputCheckBox)e.Row.Cells[0].Controls[1];
				cb.Disabled = (gv.DataKeys[e.Row.RowIndex].Values["Confirm_Yn"].ToString().Contains("Y"));

				//페이지별 합계
				ld_amount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 6;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Visible = false;
				e.Row.Cells[7].Visible = false;
				e.Row.Cells[8].Visible = false;
				e.Row.Cells[9].Text = ld_amount.ToString("#,###,##0");
				e.Row.Cells[9].Attributes.Add("class", "money");
				e.Row.Cells[10].Text = "";
				e.Row.Cells[10].Attributes.Add("class", "none");
				e.Row.Cells[10].ColumnSpan = 7;
				e.Row.Cells[11].Visible = false;
				e.Row.Cells[12].Visible = false;
				e.Row.Cells[13].Visible = false;
				e.Row.Cells[14].Visible = false;
				e.Row.Cells[15].Visible = false;
				e.Row.Cells[16].Visible = false;
				e.Row.Cells[17].Visible = false;
				e.Row.Cells[18].Visible = false;
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
			BindingGridView(sender, row.RowIndex);
		}

		//결과값 바인딩
		private void BindingGridView(object sender, int targetRow)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = gv.Rows[targetRow];

			LinkButton lbtn_rc = (LinkButton)gv.Rows[targetRow].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();											//0.체크박스
			h_no.Value = row.Cells[1].Text.ToString();								//1.번호
			lbl_pk.Text = gv.DataKeys[row.RowIndex].Values["Seq"].ToString();		//2.Seq
			ddl_search_card_cd.SelectedValue = gv.DataKeys[row.RowIndex].Values["Card_Cd"].ToString();	//3.Card_Cd
																					//4.Card_Nm
			lbl_ins_cd.Text = row.Cells[5].Text.Trim();								//5.Ins_Cd
			ddl_account.SelectedValue = gv.DataKeys[row.RowIndex].Values["Account"].ToString();	//6.Account
																					//7.Account_Nm
			txt_contents.Text = lbtn_rc.Text;										//8.Contents (template)
			txt_amount.Text = row.Cells[9].Text.Trim();								//9.Amount
			txt_ins_total_cnt.Text = row.Cells[10].Text.Trim();						//10.Ins_Total_Cnt
			h_ins_total_cnt.Value = row.Cells[10].Text.Trim();						//10.Ins_Total_Cnt - 수정시 비교용
			ce_biz_dt.SelectedDate = Convert.ToDateTime(row.Cells[11].Text.Trim());	//11.Biz_Dt

			bool lb_exist_ins_dt = false;	//할부시작일(종료일)이 있는지 여부
			if (WebControlUtil.CheckDdlValue(ddl_ins_st_dt, row.Cells[12].Text.Trim()) &&
				WebControlUtil.CheckDdlValue(ddl_ins_ed_dt, row.Cells[13].Text.Trim())
			)
			{
				lb_exist_ins_dt = true;
				ddl_ins_st_dt.SelectedValue = row.Cells[12].Text.Trim();			//12.Ins_St_Dt
				ddl_ins_ed_dt.SelectedValue = row.Cells[13].Text.Trim();			//13.Ins_Ed_Dt
			}

			txt_remark.Text = gv.DataKeys[row.RowIndex].Values["Remark"].ToString();//14.Remark
			rbl_paymnt_yn.SelectedValue = row.Cells[15].Text.Trim();				//15.Paymnt_Yn
			lbl_confirm_yn.Text = gv.DataKeys[row.RowIndex].Values["Confirm_Yn"].ToString();//16.Confirm_Yn
			txt_latitude.Text = gv.DataKeys[row.RowIndex].Values["Latitude"].ToString();	//17.Latitude
			txt_longitude.Text = gv.DataKeys[row.RowIndex].Values["Longitude"].ToString();	//18.Longitude

			//바인딩할 할부시작일(종료일)이 있으면
			if (lb_exist_ins_dt)
			{
				//할부상환리스트
				SelectRepayList(ddl_search_card_cd.SelectedValue, lbl_ins_cd.Text);

				//모드를 U로 한다.
				h_lbl_mode.Value = gs_page_mode = "U";
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_163");	//할부시작일(종료일)이 없습니다.\n설정관리에서 할부사용관리조회범위를 확인하세요
			}
		}

		#endregion

		#region GridView2이벤트

		//RowDataBound
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
			}
			
			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView2);
			sGv.RowSpanGridView(GridView2, 2);
			sGv.RowSpanGridView(GridView2, 3);
			sGv.RowSpanGridView(GridView2, 4);
			sGv.RowSpanGridView(GridView2, 5);	//비고
		}		
		
		#endregion

		#region 버튼이벤트 - 할부사용내역

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
			SetCardInfo();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_CRD_INSTALLMENT_BIZ", "Seq", lbl_pk.Text.Trim()))
			{
				if (lbl_confirm_yn.Text == "N")	//확정여부가 Y이면 수정불가
				{
					UpdateProcess();
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_108");	// 확정된 항목은 수정할 수 없습니다
				}
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					string ls_confirm_yn = GridView1.DataKeys[i].Values["Confirm_Yn"].ToString();
					sb.Append("<UPDMS_CRD_INSTALLMENT_BIZ>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("<Confirm_Yn>" + ls_confirm_yn + "</Confirm_Yn>");
					sb.Append("</UPDMS_CRD_INSTALLMENT_BIZ>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_account", typeof(string), kw2);
			lo_dp.AddProperty("ls_biz_dt_from", typeof(string), kw3);
			lo_dp.AddProperty("ls_biz_dt_to", typeof(string), kw4);

			using (Crd1013m_NT _Crd1013m_NT = new Crd1013m_NT())
			{
				li_row_count = _Crd1013m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Crd1013m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//할부시작일 계산
		protected void lbtn_ins_st_dt_Click(object sender, EventArgs e)
		{
			if (ddl_ins_st_dt.Items.Count > 0)
			{
				SetInsStartDt();
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_142");	//지정된 결제일이 없습니다.\n'카드결제일관리'에서 추가해 주세요
			}
		}

		//할부종료일 계산
		protected void lbtn_ins_ed_dt_Click(object sender, EventArgs e)
		{
			if (ddl_ins_ed_dt.Items.Count > 0)
			{
				SetInsEndDt();
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_142");	//지정된 결제일이 없습니다.\n'카드결제일관리'에서 추가해 주세요
			}			
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
			CreateInsCd();
		}

		//모드변경 U -> I
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
			CreateInsCd();
		}
		
		#endregion
		
		#region 버튼이벤트 - 할부상환관리

		//차수별할부금 계산
		protected void ibtn_calc_Click(object sender, EventArgs e)
		{
			//모드를 U로 한다.
			h_lbl_mode.Value = gs_page_mode = "U";
			
			setCalcRepayAmount();
		}

		//할부상환리스트 저장
		protected void ibtn_save_repay_Click(object sender, EventArgs e)
		{
			string ls_msg = IsValidInsRepayList();
			
			//금액 검증
			if (ls_msg == "OK")
			{
				UpdateRepayProcess();
			}
			else
			{
				h_lbl_mode.Value = gs_page_mode = "U";
				CallMsgBoxInAjax("\"" + ls_msg + "\"", null, "A");
			}
		}

		//확정(할부상환리스트에서)
		protected void lbtn_confirm_Click(object sender, EventArgs e)
		{
			using (AccessCheck access = new AccessCheck())
			{
				if (access.CheckPgmUsingGrant(USER_DIV, PID))
				{
					ConfirmProcess(Convert.ToInt32(h_seq.Value), h_confirm_yn.Value);
					SelectRepayList(ddl_search_card_cd.SelectedValue, lbl_ins_cd.Text);
					h_lbl_mode.Value = gs_page_mode = "U";	//모드를 U로 한다.
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_109");	//작업에 필요한 권한이 없습니다
				}
			}
		}

		#endregion

	}
}